package com.software.car.controller;

import com.software.car.common.enums.ResultEnum;
import com.software.car.common.utils.CommonPage;
import com.software.car.common.utils.CommonResult;
import com.software.car.entity.dto.request.UserInsertRequest;
import com.software.car.entity.dto.response.UserResponse;
import com.software.car.api.UserService;
import com.software.car.entity.po.UserPo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

/**
 * @Author 魔法はまだ解けない、林涛
 * @Date 2021/1/21
 */
@RestController
@RequestMapping("/user")
public class UserController {
    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    UserService userService;

    /**
     * 超级管理员
     * 获取所有用户信息，包括密码
     * 默认获取正常状态用户
     *
     * @param page  页号
     * @param pageSize  页大小
     * @param state 用户状态，null为全部用户
     * @return
     */
    @GetMapping("/administer/users/page")
    @PreAuthorize("hasAnyRole('ROLE_ADMINISTER')")
    public CommonResult getUsersByPage(@RequestParam(value = "page", required = false) Integer page,
                                       @RequestParam(value = "pageSize", required = false) Integer pageSize,
                                       @RequestParam(value = "state", required = false) Integer state) {
        logger.info("执行类——UserController 执行方法——getUsersByPage()");
        if (page == null) {
            page = 1;
        }
        if (pageSize == null) {
            pageSize = 10;
        }
        if (state == null) {
            state = null;
        }
        CommonPage usersByPage = userService.getUsersByPage(page, pageSize, state);
        return CommonResult.success(usersByPage);
    }

    /**
     * 用户
     * 获取个人信息
     *
     * @param userPo 个人信息
     * @return
     */
    @GetMapping("/personal/message")
    @PreAuthorize("hasAnyRole('ROLE_ADMINISTER','ROLE_USER')")
    public CommonResult getPersonalMessage(@RequestAttribute("user") UserPo userPo) {
        logger.info("执行类——UserController 执行方法——getPersonalMessage()");
        UserResponse build = UserResponse.builder()
                .id(userPo.getId())
                .name(userPo.getName())
                .sex(userPo.getSex())
                .account(userPo.getAccount())
                .img(userPo.getImg())
                .role(userPo.getRole())
                .state(userPo.getState())
                .email(userPo.getEmail())
                .phone(userPo.getPhone())
                .createTime(userPo.getCreateTime())
                .updateTime(userPo.getUpdateTime())
                .build();
        return CommonResult.success(build);
    }

    /**
     * 管理员
     * 添加新用户
     *
     * @param userInsertRequest
     * @return
     */
    @PostMapping("/administer/user")
    @PreAuthorize("hasAnyRole('ROLE_ADMINISTER')")
    public CommonResult addUser(@RequestBody UserInsertRequest userInsertRequest) {
        logger.info("执行类——UserController 执行方法——addUser()");
        //检验账号是否存在
        UserResponse userByAccount = userService.getUserByAccount(userInsertRequest.getAccount());
        if (userByAccount != null) {
            return CommonResult.fail(ResultEnum.ACCOUNT_HAS_EXIT);
        }
        int i = userService.insertUser(userInsertRequest);
        if (i == 0) {
            return CommonResult.fail(ResultEnum.INSERT_USER_FAIL);
        }
        return CommonResult.success();
    }

    /**
     * 个人
     * 用户信息修改
     *
     * @param userInsertDto 前端给的个人数据体
     * @return
     */
    @PutMapping("/personal/message")
    @PreAuthorize("hasAnyRole('ROLE_ADMINISTER','ROLE_USER')")
    public CommonResult userUpdateUser(@RequestBody UserPo userInsertDto, @RequestAttribute("user") UserPo userPo) {
        UserResponse userResponse = userService.userUpdateUser(userInsertDto, userPo);
        return CommonResult.success(userResponse);
    }


    /**
     * 管理员
     * 修改用户信息
     * 不能改自己的
     *
     * @param userInsertDto 前端给的修改的用户数据体
     * @return
     */
    @PutMapping("/administer/message")
    @PreAuthorize("hasAnyRole('ROLE_ADMINISTER','ROLE_USER')")
    public CommonResult administerUpdateUser(@RequestBody UserPo userInsertDto,
                                             @RequestAttribute("user") UserPo userPo) {
        if (userInsertDto.getId() == null) {
            return CommonResult.fail(ResultEnum.PARAMS_NOT_FOUND);
        }
        if (userInsertDto.getId() == userPo.getId()) {
            return CommonResult.fail(ResultEnum.ADMINISTER_UPDATE_ERROR);
        }
        UserResponse userByAccount = userService.getUserByAccount(userInsertDto.getAccount());
        if (userByAccount != null) {
            return CommonResult.fail(ResultEnum.ACCOUNT_HAS_EXIT);
        }
        UserResponse userResponse = userService.administerUpdateUser(userInsertDto);
        return CommonResult.success(userResponse);
    }

    /**
     * 个人用户密码修改
     *
     * @param oldPassword
     * @param newPassword
     * @param userPo
     * @return
     */
    @PutMapping("/personal/password")
    @PreAuthorize("hasAnyRole('ROLE_ADMINISTER','ROLE_USER')")
    public CommonResult userUpdatePassword(@RequestParam(value = "oldPassword") String oldPassword, @RequestParam(value = "newPassword") String newPassword, @RequestAttribute("user") UserPo userPo) {
        if (userPo.getPassword().equals(oldPassword)) {
            UserPo userPo1 = new UserPo();
            userPo1.setPassword(newPassword);
            UserResponse userResponse = userService.updateUser(userPo1, userPo);
            return CommonResult.success(userResponse);
        } else {
            return CommonResult.fail(ResultEnum.UPDATE_ERROR);
        }
    }

    /**
     * 管理员用户注销功能
     *
     * @param id
     * @return
     */
    @DeleteMapping("/administer/users/delete")
    @PreAuthorize("hasAnyRole('ROLE_ADMINISTER')")
    public CommonResult deleteUser(@RequestParam String id,
                                   @RequestAttribute("user") UserPo me) {
        if (id == me.getId()) {
            return CommonResult.fail(ResultEnum.ADMINISTER_UPDATE_ERROR);
        }
        UserPo userPo = userService.getUserPo(id);
        if (userPo == null) {
            return CommonResult.fail(ResultEnum.UPDATE_ERROR);
        }
        userPo.setState(2);
        UserResponse userResponse = userService.administerUpdateUser(userPo);
        return CommonResult.success(userResponse);
    }

    /**
     * 管理员激活用户
     *
     * @param id
     * @return
     */
    @PutMapping("/administer/users/activation")
    @PreAuthorize("hasAnyRole('ROLE_ADMINISTER')")
    public CommonResult activationUser(@RequestParam String id,
                                       @RequestAttribute("user") UserPo me) {
        if (id == me.getId()) {
            return CommonResult.fail(ResultEnum.ADMINISTER_UPDATE_ERROR);
        }
        UserPo userPo = userService.getUserPo(id);
        userPo.setState(1);
        UserResponse userResponse = userService.administerUpdateUser(userPo);
        return CommonResult.success(userResponse);
    }
}